package cc.momas.momall.search.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cc.momas.common.vo.SearchResult;
import cc.momas.momall.search.service.SearchService;

@Controller
public class SearchController {

	@Autowired
	private SearchService searchService;
	@Value("${SEARCH_RESULT_ROWS}")
	private Integer SEARCH_RESULT_ROWS;

	@RequestMapping("/search.html")
	public String searchItemList(String keyword, @RequestParam(defaultValue = "1") Integer page, Model model) {
		try {
			if (keyword == null || "".equals(keyword.trim())) {
				// 如果没有传关键字过来,就查询所有商品
				keyword = "*";
			}
			keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
			// 查询商品列表
			SearchResult search = searchService.search(keyword, page, SEARCH_RESULT_ROWS);
			// 把结果传递给页面
			model.addAttribute("query", keyword);
			model.addAttribute("totalPages", search.getTotalPages());
			model.addAttribute("recourdCount", search.getRecordCount());
			model.addAttribute("itemList", search.getItemList());
			// 返回逻辑视图
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "search";
	}
	
	@RequestMapping("/index.html")
	public String toIndex() {
		return "search";
	}

}
